package com.sgb.kjwl.view.ui.fragment.pick;

import androidx.databinding.DataBindingUtil;

import android.os.Build;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;

import com.apeng.permissions.EsayPermissions;
import com.apeng.permissions.OnPermission;
import com.chuanglan.shanyan_sdk.OneKeyLoginManager;
import com.chuanglan.shanyan_sdk.listener.OneKeyLoginListener;
import com.chuanglan.shanyan_sdk.listener.OpenLoginAuthListener;
import com.sgb.alimaplibrary.util.ToastUtil;
import com.swgk.core.base.AppFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.GsonManager;
import com.sgb.kjwl.databinding.FragmentPickCompanyListBinding;
import com.sgb.kjwl.di.pick.DaggerPickFragComponent;
import com.sgb.kjwl.di.pick.PickFragModule;
import com.sgb.kjwl.model.entity.LoginEntity;
import com.sgb.kjwl.view.widget.pick.PickPopWindowView;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.kjwl.model.entity.UserMsgEntity;
import com.sgb.kjwl.model.entity.user.OneKeyLoginEntity;
import com.sgb.kjwl.model.entity.user.PickCompanyListEntity;
import com.sgb.kjwl.utils.ConfigUtils;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LoginEvent;
import com.sgb.kjwl.view.ui.activity.manage.WebsiteInfoActivity;
import com.sgb.kjwl.view.ui.activity.pick.PickSearchActivity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.kjwl.view.ui.adapter.pick.PickCompanyListAdapter;
import com.swgk.core.mmkvutil.CacheMarker;
import com.sgb.kjwl.view.widget.PickHallBidingPopWindow;
import com.sgb.kjwl.viewmodel.pick.PickCompanyModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.decoration.RecyclerCustomDecoration;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.view.areapopup.AddressEntity;
import com.swgk.core.view.areapopup.GoodsSourceLocationEntity;
import com.swgk.core.view.areapopup.ThreeLevelAreaWindow;
import com.swgk.core.xrecyclerview.XRecyclerView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import static com.sgb.kjwl.view.ui.fragment.pick.PickRequireListFragment3.PERMISSIONS;

/**
 * 招采/搜索/企业
 */
public class PickCompanyListFragment extends AppFragment {

    public static final String KEY_TYPE = "type";
    public static final String KEY_TOTAL = "total";
    private FragmentPickCompanyListBinding binding;
    @Inject
    PickCompanyModel viewModel;
    //搜索关键字
    private String searchName = "";
    private PickSearchActivity pickSearchActivity;
    private int total;
    private int page = 1;

    private PickCompanyListAdapter pickCompanyListAdapter;
    private ThreeLevelAreaWindow mAddressPop;
    private PickHallBidingPopWindow pickTypePopWindow;
    private PickHallBidingPopWindow pickModelPopWindow;
    private boolean isChangeArea;
    private boolean isChangeType;
    private boolean isChangeModel;

    private List<PickSelectEntity> scaleDatas = new ArrayList<>();
    private List<PickSelectEntity> typeDates = new ArrayList<>();
    private List<PickSelectEntity> provinceDates = new ArrayList<>();
    private List<PickSelectEntity> cityDates = new ArrayList<>();

    //地区
    private List<String> citysNo = new ArrayList<>();
    //规模
    private List<String> scalesNo = new ArrayList<>();
    private InputMethodManager im;

    //省
    private String areaCode;
    private String areaName;
    //地区
    private String cityNo;
    //类型
    private String typeNo;
    private String typeName;
    //规模
    private String modelNo;
    private String modelName;

    private Boolean isSearching = false;
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> scrData;
    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerPickFragComponent.builder()
                .appComponent(appComponent)
                .pickFragModule(new PickFragModule(this))
                .build()
                .inject(this);
    }

    public static PickCompanyListFragment newInstance(String type, int total) {
        PickCompanyListFragment fragment = new PickCompanyListFragment();
        Bundle bundle = new Bundle();
        bundle.putString(KEY_TYPE, type);
        bundle.putInt(KEY_TOTAL, total);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_pick_company_list, container, false);
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        searchName = (String) getArguments().get(KEY_TYPE);
        total = getArguments().getInt(KEY_TOTAL, 0);
        pickSearchActivity = (PickSearchActivity) getActivity();
        initView();
        initData();
    }

    private void initView() {
        pickSearchActivity.showTopBack(false);
        binding.tvType.setOnClickListener(this);
        binding.tvArea.setOnClickListener(this);
        binding.tvModel.setOnClickListener(this);

        // 类型
        pickTypePopWindow = new PickHallBidingPopWindow(getActivity());
        pickTypePopWindow.setBgView(binding.grayLayout);
        pickTypePopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                typeNo = ((PickSelectEntity) key1).getNo();
                typeName = ((PickSelectEntity) key1).getProjectscale();
                if (!"全部".equals(typeName)) {
                    isChangeType = true;
                    updateChooseTextStatus(binding.tvType,1,typeName);
                }else{
                    isChangeType = false;
                    updateChooseTextStatus(binding.tvType,0,"经营类型");
                }
                initData();
            }
        });
        pickTypePopWindow.setOnDisMissClick(new BasePopWindow.OnDisMiss() {
            @Override
            public void disMiss() {
                if (!isChangeType) {
                    updateChooseTextStatus(binding.tvType,0,"经营类型");
                } else {
                    updateChooseTextStatus(binding.tvType,1,typeName);
                }
            }
        });
        // 规模
        pickModelPopWindow = new PickHallBidingPopWindow(getActivity());
        pickModelPopWindow.setBgView(binding.grayLayout);
        pickModelPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                modelNo = ((PickSelectEntity) key1).getNo();
                modelName = ((PickSelectEntity) key1).getProjectscale();
                if(!"全部".equals(modelName)){
                    isChangeModel = true;
                    updateChooseTextStatus(binding.tvModel,1,modelName);
                }else{
                    isChangeModel = false;
                    updateChooseTextStatus(binding.tvModel,0,"招采规模");
                }
                initData();
            }
        });
        pickModelPopWindow.setOnDisMissClick(new BasePopWindow.OnDisMiss() {
            @Override
            public void disMiss() {
                if (!isChangeModel) {
                    updateChooseTextStatus(binding.tvModel,0,"招采规模");
                } else {
                    updateChooseTextStatus(binding.tvModel,1,modelName);
                }
            }
        });

        if (pickCompanyListAdapter == null) {
            pickCompanyListAdapter  = new PickCompanyListAdapter(getActivity(), null, new PickCompanyListAdapter.CallBack(){
                @Override
                public void onItemFocus(PickCompanyListEntity entity, int position) {
                    if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                        jumpLogin();
                    } else {
                        viewModel.userFocus(entity.getCompanyNo(),!entity.getFocus(),position);
                    }
                }
            });
        }
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        binding.recyclerView.setLayoutManager(layoutManager);
        binding.recyclerView.addItemDecoration(new RecyclerCustomDecoration(0, 0, 0, getActivity().getResources().getDimension(R.dimen.dp1), getActivity().getResources().getColor(R.color.color_F5F5F5)));
        binding.recyclerView.setAdapter(pickCompanyListAdapter);
        binding.recyclerView.setLoadingMoreEnabled(true);
        binding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                page = 1;
                viewModel.findTenderEnterprisePage(searchName,modelNo,typeNo,cityNo,areaCode,total,page);
                binding.recyclerView.setLoadingMoreEnabled(true);
            }

            @Override
            public void onLoadMore() {
                if (pickCompanyListAdapter.getDatas().size() < total){
                    page ++;
                    viewModel.findTenderEnterprisePage(searchName,modelNo,typeNo,cityNo,areaCode,total,page);
                }else {
                    binding.recyclerView.setLoadingMoreEnabled(false);
                }
            }
        });

        pickCompanyListAdapter.setOnItemClick(new AdapterOnItemClick<PickCompanyListEntity>() {
            @Override
            public void onItemClick(PickCompanyListEntity pickCompanyListEntity, int position) {
                if (TextUtils.isEmpty(String.valueOf(pickCompanyListEntity.getCompanyNo()))) {
                    ToastUtil.show(getActivity(), "企业店铺no不能为空");
                    return;
                }
                WebsiteInfoActivity.start(getActivity(), String.valueOf(pickCompanyListEntity.getCompanyNo()), WebsiteInfoActivity.WEBSITE_FOR_COMPANY);
            }
        });

        viewModel.getSelecteScaleData();
        viewModel.getProvinceData();
        viewModel.getServiceTypeList();
        initAddressPopup();
    }

    private void initAddressPopup() {
        mAddressPop = new ThreeLevelAreaWindow(getActivity());
        mAddressPop.setMemberHeight();
        mAddressPop.setCitySingle();
        mAddressPop.setProvinceSingle();
        mAddressPop.setShowSimpleName(true);
        mAddressPop.setOnlyShowProAndCity(true);
        mAddressPop.setAllSingleSelect(true);
        mAddressPop.setThreeListIsGone(true);
        mAddressPop.setBgView(binding.grayLayout);
        mAddressPop.setOnResultClick(new ThreeLevelAreaWindow.OnResultClickProxy() {
            @Override
            protected void result(GoodsSourceLocationEntity entity) {
                areaCode = entity.getProvinceNo();
                if (!TextUtils.isEmpty(entity.getProvinceNo())) {
                    areaName = entity.getProvinceName();
                    areaCode = entity.getProvinceNo();
                    cityNo = "";
                    if ("0".equals(areaCode)) {
                        areaName = "地区";
                    }
                    updateChooseTextStatus(binding.tvArea, 1, areaName);
                    if (!TextUtils.isEmpty(entity.getCityNo())) {
                        cityNo = entity.getCityNo();
                        areaName = entity.getCityName();
                        viewModel.getAddressCityData(scrData, cityNo);
                        updateChooseTextStatus(binding.tvArea, 1, areaName);
                    }
                } else {
                    areaName = "地区";
                    areaCode = "";
                    cityNo = "";
                    updateChooseTextStatus(binding.tvArea, 0, areaName);
                }
                initData();


            }
        });
        mAddressPop.setOnDismissListener(() -> {
            updateChooseTextStatus(binding.tvArea, "地区".equals(areaName) ? 0 : 1, areaName);
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_type:
                showTypePopWindow();
                break;
            case R.id.tv_model:
                showModelPopWindow();
                break;
            case R.id.tv_area:
                showProvincePopWindow();
                break;
        }
    }

    /**
     * 省份
     */
    private void showProvincePopWindow() {
        if(TextUtils.isEmpty(areaName)){
            areaName = "地区";
        }
        updateChooseTextStatus(binding.tvArea, TextUtils.isEmpty(areaCode) && TextUtils.isEmpty(cityNo) ? -1 : -2, areaName);
        mAddressPop.showPopwindow0(binding.tvArea);
    }

    private void showTypePopWindow() {
        if(TextUtils.isEmpty(typeName)){
            typeName = "经营类型" ;
            pickTypePopWindow.setDefItem();
        }
        updateChooseTextStatus(binding.tvType, -1, typeName);
        pickTypePopWindow.showPopwindow(binding.tvType);
        pickTypePopWindow.setData(typeDates,false);
    }

    private void showModelPopWindow() {
        if(TextUtils.isEmpty(modelName)){
            modelName = "招采规模" ;
            pickModelPopWindow.setDefItem();
        }
        updateChooseTextStatus(binding.tvModel, -1, modelName);
        pickModelPopWindow.showPopwindow(binding.tvModel);
        pickModelPopWindow.setData(scaleDatas,false);
    }

    public void setProvinceDatas(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
        if (data != null && data.size() > 0) {
            scrData = data;
            mAddressPop.setData(scrData, true);
        } else {
            viewModel.getAddressCityData(scrData, cityNo);
        }
    }

    public void setCityDatas(List<PickSelectEntity> data) {
        cityDates.clear();
        cityDates.addAll(data);
        mAddressPop.setData(scrData, false);
    }

    public void setTypeDatas(List<PickSelectEntity> datas){
        typeDates.clear();
        datas.add(0,new PickSelectEntity("","全部"));
        typeDates.addAll(datas);
    }

    public void setScaleDatas(List<PickSelectEntity> datas){
        scaleDatas.clear();
        datas.add(0,new PickSelectEntity("","全部"));
        scaleDatas.addAll(datas);
    }
    
    public void fullScroll(){
        binding.neSc.fullScroll(View.FOCUS_UP);
    }

    private void initData() {
        viewModel.findTenderEnterprisePage(searchName,modelNo,typeNo,cityNo,areaCode,total,page);
    }

    public void showData(List<PickCompanyListEntity> list){
        binding.recyclerView.refreshComplete();
        if (list == null || list.size() == 0) {
            binding.recyclerView.setVisibility(View.GONE);
            binding.emptyView.setVisibility(View.VISIBLE);
        }else {
            binding.recyclerView.setVisibility(View.VISIBLE);
            binding.emptyView.setVisibility(View.GONE);
            pickCompanyListAdapter.setDatas(list);
        }
    }

    public void showMoreData(List<PickCompanyListEntity> list){
        binding.recyclerView.loadMoreComplete();
        binding.emptyView.setVisibility(View.GONE);
        pickCompanyListAdapter.addDatas(list);
    }

    public void emptyView(){
        binding.recyclerView.refreshComplete();
        binding.recyclerView.loadMoreComplete();
        binding.emptyView.setVisibility(View.VISIBLE);
    }

    /**
     * 更新选项颜色
     */
    private void updateChooseTextStatus(PickPopWindowView pickPopWindowView, int value, String name) {
        if (!TextUtils.isEmpty(name)) {
            if (name.length() > 4) {
                name = name.substring(0, 4) + "...";
            }
        }
        if (value == -1 || value == -2) {
            binding.popLine.setVisibility(View.VISIBLE);
            pickPopWindowView.setChooseData(R.drawable.member_pop_blue_bg2, R.mipmap.ic_up_arrow_n, R.color.color_333333,true,name);
        }else if (value == 0) {
            binding.popLine.setVisibility(View.GONE);
            pickPopWindowView.setChooseData(R.drawable.search_bg, R.mipmap.ic_down_arrow_n, R.color.color_333333,false,name);
        } else {
            binding.popLine.setVisibility(View.GONE);
            pickPopWindowView.setChooseData(R.drawable.search_new_blue_bg_10, R.mipmap.icon_down_red, R.color.color_main,false,name);
        }
    }

    public void setIsGz(boolean isGz, int position) {
        pickCompanyListAdapter.getDatas().get(position).setFocus(isGz);
        pickCompanyListAdapter.notifyDataSetChanged();
    }

    public void jumpLogin() {
        boolean shanyan = MkvUtils.get().getBoolean(MkvUtils.CommomData, CacheMarker.ShanYan, false);
        if (shanyan) {
            //校验权限
            //申请动态权限
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                //6.0以上运行时权限处理
                EsayPermissions.with(getActivity()).constantRequest().permission(PERMISSIONS).request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {
                        openLoginPage();
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        openLoginPage();
                    }
                });

            } else {
                //有权限
                openLoginPage();
            }

        } else {
            VerificationCodeLoginActivity.start(getActivity(), false);
        }
    }

    /**
     * 拉起授权页
     */
    private void openLoginPage() {
        //设置授权页样式
        OneKeyLoginManager.getInstance().setAuthThemeConfig(ConfigUtils.getCJSConfig(getActivity()));
        //开始拉取授权页
        DialogHelper.showProgressDialog(getActivity(), null, "数据加载中", 0, true, null).setCanceledOnTouchOutside(true);
        OneKeyLoginManager.getInstance().openLoginAuth(false, new OpenLoginAuthListener() {
            @Override
            public void getOpenLoginAuthStatus(int code, String result) {
                DialogHelper.dismissProgressDialog();
                if (code != 1000) {
                    VerificationCodeLoginActivity.start(getActivity(), false);
                }
            }
        }, new OneKeyLoginListener() {
            @Override
            public void getOneKeyLoginStatus(int code, String result) {
                DialogHelper.dismissProgressDialog();
                if (code == 1000) {
                    OneKeyLoginEntity oneKeyLoginEntity = GsonManager.getInstance().getGson().fromJson(result, OneKeyLoginEntity.class);
                    oneKeyLoginEntity.setPlateform("Android");
                    viewModel.oneKeyLogin(oneKeyLoginEntity);
                }
            }
        });
    }

    /**
     * 一键登录成功
     *
     * @param loginEntity
     * @param phoneNumber
     */
    public void loginSucceed(LoginEntity loginEntity, String phoneNumber) {
        LoginEvent loginEvent = new LoginEvent();
        loginEvent.setMessageData(phoneNumber);
        loginEvent.setMessageTag(EventConstant.EVENT_LOGIN);
        loginEvent.setObject(loginEntity);
        EventBus.getDefault().postSticky(loginEvent);
    }

    public void getUserMsgSucceed(UserMsgEntity userMsgEntity) {
        LoginEvent loginEvent = new LoginEvent();
        loginEvent.setMessageTag(EventConstant.EVENT_USER_MSG);
        loginEvent.setMessageData(userMsgEntity);
        EventBus.getDefault().postSticky(loginEvent);
    }
}
